﻿using System;
using System.Collections.Generic;
using ZhCun.DbCore;
using ZhCun.DbCore.BuildSQLText;
using ZhCun.DbCore.Entitys;
using ZhCun.WebCommon.DBModels;

namespace ZhCun.WebCommon.AL
{
    /// <summary>
    /// 数据权限处理
    /// </summary>
    public class DataRightsHelper
    {
        static readonly Dictionary<Type, Action<ISqlBuilder, EmDbOperation, TSysLoginToken>> DataHandlerDict = new Dictionary<Type, Action<ISqlBuilder, EmDbOperation, TSysLoginToken>>();

        static Action<ISqlBuilder, EmDbOperation, TSysLoginToken> DefaultDataHandler;

        /// <summary>
        /// 增加指定的数据权限接口
        /// </summary>
        public static void AddDataRights<TEntity>(Action<ISqlBuilder, EmDbOperation, TSysLoginToken> dataHandle) where TEntity : EntityBase, new()
        {
            var type = typeof(TEntity);
            DataHandlerDict[type] = dataHandle;
        }        
        /// <summary>
        /// 数据权限处理
        /// </summary>
        internal static void DataRightsHandler<TEntity>(ISqlBuilder sqlBuilder, EmDbOperation opType, TSysLoginToken loginState) where TEntity : EntityBase, new()
        {
            DefaultDataHandler?.Invoke(sqlBuilder, opType, loginState);
            foreach (var item in DataHandlerDict.Keys)
            {
                if (item == typeof(TEntity))
                {
                    DataHandlerDict[item](sqlBuilder, opType, loginState);
                }
            }
        }
    }
}